<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
    @load="onLoad"
  >
    <!-- <van-cell v-for="(item, index) in list" :key="index">
      {{ item.content }}
    </van-cell> -->
    <CommentItem v-for="(item) in list" :key="item.com_id" :comment="item" @reply-click="$emit('reply-click',$event)"/>
  </van-list>
</template>

<script>
/*
  目标1: 当请求完数据后, 将文章评论总数传递给父组件
  1. 在onload方法中,请求完成后,主动触发父组件的自定义事件,将总数传给父组件
*/
import { getCommentsAPI } from '../../../api/index.js'
import CommentItem from './commentItem.vue'
export default {
  name: 'commentList',
  props: {
    type: { // a:评论/c回复 评论类型
      type: String,
      default: 'a'
    },
    sourceId: { // 文章id或评论id
      type: String,
      default: ''
    }
  },
  components: {
    CommentItem
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      offset: null // 翻页偏移量, 如有id,就用id
    }
  },
  methods: {
    async onLoad () {
      try {
        const res = await getCommentsAPI({
          type: this.type,
          source: this.sourceId,
          offset: this.offset,
          limit: 3
        })
        console.log(res)
        this.list.push(...res.data.data.results)
        // 把评论总数传给父组件
        this.$emit('onloadSuccess', res.data.data.total_count)
        this.loading = false
        if (res.data.data.results.length === 0) {
          this.finished = true
        } else {
          this.offset = res.data.data.last_id
        }
      } catch (error) {
        console.log(error)
        this.error = true
        this.loading = false
      }
    },
    // 父组件将会调用添加list头部元素
    unshiftComment (item) {
      this.list.unshift(item)
    }
  }
}
</script>

<style lang="less" scoped>

</style>
